import type { RouteRecord } from "vue-router";
export function getAdminSystem() {
  const user = useUserStore();
  let systemName = "";
  if (user.token) {
    const route = useRoute();
    const routeName = route.name as string;
    const menuTree = user.menuTree;
    // 通过树，找到当前页面的根节点
    const system = getSystem(routeName, menuTree);
    if (system) {
      systemName = system.name;
    }
  }
  return systemName;
}

function getSystem(routeName: string, menuTree: Menu[]): Menu | null {
  for (const system of menuTree) {
    // 深度优先搜索检查当前系统是否包含目标叶子
    if (hasLeaf(system, routeName)) {
      return system;
    }
  }
  return null;
}

function hasLeaf(node: Menu, targetName: string): boolean {
  // 当前节点是叶子节点时直接比较
  if (!node.children || node.children.length === 0) {
    return node.name === targetName;
  }

  // 非叶子节点时递归检查子节点
  return node.children.some((child) => hasLeaf(child, targetName));
}

export function getAdminSystemList(menuList: Menu[]) {
  return menuList.filter((menu) => menu.children && menu.children.length > 0);
}

export function replenishMenuPath(
  menuList: Menu[],
  routeMap: Map<string, RouteRecord>
) {
  return menuList.forEach((menu) => {
    menu.path = routeMap.get(menu.name)?.path;
    if (menu.children && menu.children.length > 0) {
      replenishMenuPath(menu.children, routeMap);
    }
  });
}

export function getAdminMenuListBySystem(
  systemName: string,
  systemList: Menu[]
) {
  const system = systemList.find((system) => system.name === systemName);
  if (system) {
    return system.children;
  } else {
    return null;
  }
}
